<?php
/**
 * Created by PhpStorm.
 * User: worry
 * Date: 2016/12/28
 * Time: 22:40
 */

namespace backend\controllers;


use backend\models\UserSearch;
use common\components\Error;
use common\controllers\BaseController;
use backend\services\UserService;
use Yii;
use yii\helpers\Url;
use yii\web\Response;

class LoginController extends BaseController
{
    public $layout = false;

    /**
     * 登录
     * @return string
     * @throws \Exception
     */
    public function actionIndex()
    {
        $request = Yii::$app->request;
        if ($request->isPost) {
            $resp = Error::tryCatch(function () use ($request) {
                $post = $request->post();
                $UserService = new UserService();
                $rs = $UserService->login($post, Yii::$app->session->name);
                if (!$rs) {
                    Error::exception('登录失败', Error::LOGIN_FAILED);
                }
                if ($request->isAjax) {
                    return $this->success('登录成功', [], Url::toRoute('index/index'));
                } else {
                    $this->redirect(['index/index'])->send();
                    exit;
                }
            });
            return $this->ajaxArray($resp);
        }

        if ($this->userInfo) {
            return $this->redirect('index/index');
        }
        return $this->render('index');
    }

    /**
     * 注销
     */
    public function actionLogout()
    {
        Error::tryCatch(function () {
            $UserService = new UserService();
            $UserService->logout('admin');
        });
        return $this->redirect(['/login/index'])->send();
    }

}